/**
 * 常用工具类
 */

/**
 * Here文档
 * 
 * @param fn 
 * @param 参数
 */
function heredoc(fn) {
  var doc = fn.toString().replace(/^[^\/]+\/\*!?\s?/, '')
    .replace(/\*\/[^\/]+$/, '').trim().replace(/>\s*</g, '><');
  for (var i = 1; i <arguments.length; ++i) {
    while (true) {
      var j = doc.indexOf("${" + (i-1) + "}");
      if (j >= 0) {
        doc = doc.replace("${" + (i-1) + "}", arguments[i]);
      } else {
        break;
      }
    }
  }
  return doc;
}

String.prototype.gblen = function() {  
  var len = 0;  
  for (var i=0; i<this.length; i++) {  
    if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {  
       len += 2;  
     } else {  
       len ++;  
     }  
   }  
  return len;  
}

/**
 * 判断两个时间是否为同一周
 */
function isSameWeek(old,now) {  
  var oneDayTime = 1000*60*60*24;  
  var old_count = parseInt(old.getTime()/oneDayTime);  
  var now_other = parseInt(now.getTime()/oneDayTime);  
  return parseInt((old_count+4)/7) == parseInt((now_other+4)/7);  
}

let WEEKS_CN = ["日","一","二","三","四","五","六"];

function formatSimpleDate(v) {
  let now = new Date();
  let yd = new Date(now.getTime()-24*60*60*1000);
  let tw = new Date(now.getTime()+24*60*60*1000);
  
  let d = new Date(v);
  
  if (now.getFullYear() != d.getFullYear()) {
    // 如果年份不相等，直接格式化
    return d.format('yyyy年MM月dd日');
  } else if ((yd.getMonth() == d.getMonth()) && (yd.getDate() == d.getDate())){        
    // 昨天 
    return "昨天";
  } if ((now.getMonth() == d.getMonth()) && (now.getDate() == d.getDate())){
    // 今天
    return "今天";
  } if ((tw.getMonth() == d.getMonth()) && (tw.getDate() == d.getDate())){
    // 明天
    return "明天";
  } if (isSameWeek(now, d)) {
    // 是否为同一周
    return "周" + WEEKS_CN[d.getDay()];
  } else {
    return d.format('MM月dd日');
  }
}


var CommonTools = {
  
  methods: {
    /**
     * http get
     */
    get(url) {
      var self = this;
      var index = layer.load();
      return this.$http.get(url).then((resp) => {
        layer.close(index);
        console.log(resp);
        var data = resp.data;
        if (!data){
          throw "数据异常，请联系管理员";
        }
        if (!data.success) {
          throw data.msg;          
        } else {
          return data.obj;
        }
      }, (err) => {
        layer.close(index);
        throw "网络异常，请检查网络";
      });
    },
    
    /**
     * http post
     */
    post(url, data) {
      var self = this;
      var index = layer.load();
      return this.$http.post(url, data).then((resp) => {
        layer.close(index);
        console.log(resp);
        var data = resp.data;
        if (!data){
          throw "数据异常，请联系管理员";
        }
        if (!data.success) {
          throw data.msg;          
        } else {
          return data.obj;
        }
      }, (err) => {
        layer.close(index);
        throw "网络异常，请检查网络";
      });
    },
    
    /** 取查询参数 */
    getQueryParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      } else {
        return null;
      }
    },
    
    /**
     * 显示提示信息
     */
    showMsg(msg, cb) {
      this.getLayer().msg(msg? msg: '操作成功', {
        time: 2000,
        offset: 't',
        anim: 6
      }, function(){
        cb && cb();
      });
    },
    
    /**
     * 显示错误信息
     */
    showError(err) {
      if (err && typeof(err) == 'object') {
        err = err.toString();
      }
      this.getLayer().alert(err? err: '操作失败', {icon: 5});
    },
    
    /**
     * 提示信息
     */
    confirm : function(msg, ok, cacenl) {      
      var index = this.getLayer().confirm(msg, function() {
        layer.close(index);
        if (ok) {
          ok();
        }
      }, function() {
        layer.close(index);
        if (cacenl) {
          cacenl();
        }
      });
    },
    
    getLayer() {
      var player = layer;
      if (window.parent.layer) {
        player = window.parent.layer;
      }
      return player;
    },
    
    trimToString(s) {
      return $.trim(s);      
    },
    
    trimToNull(s) {
      var v = this.trimToString(s);
      return v? v: null;
    },
    
  },
  
  filters: {
    
    /**
     * 格式化简单日期
     * 
     * @param v 日期
     */
    simpleDate(v) {
      return v? formatSimpleDate(v): '';
    },
    
    /**
     * 格式化简单日期+时间格式
     * 
     * @param v 日期+时间
     */
    simpleDateTime(v) {
      if (!v) {
        return '';
      } else {
        let d = new Date(v);
        return formatSimpleDate(v) + d.format(" hh:mm"); 
      }
    },
    
    formatDateTime(v) {
     return v? new Date(v).format(): '';
    },
    
    formatDate(v) {
      return v? new Date(v).format('yyyy-MM-dd'): '';
     },
    
  }
  
};